package com.xiaoyang.forum.controller;


import cn.hutool.core.util.StrUtil;
import com.xiaoyang.forum.common.code.Result;
import com.xiaoyang.forum.common.code.ResultCode;
import com.xiaoyang.forum.common.util.JWTUtil;
import com.xiaoyang.forum.domain.dto.ArticleReplyDTO;
import com.xiaoyang.forum.domain.vo.ArticleReplyUserVO;
import com.xiaoyang.forum.service.IArticleReplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author XiaoYang
 * @since 2025-08-19
 */
@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {

    @Autowired
    private IArticleReplyService articleReplyService;

    /**
     * 发布讨论
     * @param token
     * @param articleReplyDTO
     * @return
     */
    @PostMapping("/create")
    public Result<Void> create(@RequestHeader String token,
                               @RequestBody ArticleReplyDTO articleReplyDTO) {
        log.info("发布讨论");
        if (StrUtil.isEmpty(token)) {
            return Result.failed(ResultCode.USER_NO_LOGIN);
        }
        long userId = (long) JWTUtil.getUserIdFromToken(token);

        if (articleReplyDTO.getReplyId() == null && articleReplyDTO.getReplyUserId() == null) {
            // 发布评论
            articleReplyService.create(userId, articleReplyDTO.getArticleId(), articleReplyDTO.getContent());
        } else {
            // 回复评论
            articleReplyService.reply(userId, articleReplyDTO.getArticleId(), articleReplyDTO.getReplyId(),
                    articleReplyDTO.getReplyUserId(), articleReplyDTO.getContent());
        }

        return Result.success();
    }

    /**
     * 获取文章的回复列表
     * @param articleId
     * @return
     */
    @GetMapping("/toList")
    public Result<List<ArticleReplyUserVO>> toList(Long articleId) {
        log.info("获取文章的回复列表");
        List<ArticleReplyUserVO> articleReplyVOList = articleReplyService.toList(articleId);
        return Result.success(articleReplyVOList);
    }
}
